#include "maxq_config.h"
#include "comm/maxq_comm.h"
#include "tick.h"

/***** Definitions *****/
#define WUT_FREQ          (XTAL_FREQ / 1024)
#define TICKS_PER_SECOND  10   // 100 ms
#define WUT_VALUE         (WUT_FREQ / TICKS_PER_SECOND)

/***** Global Data *****/
volatile int flag_100ms;
volatile int flag_200ms;
volatile int flag_400ms;
volatile int flag_13s;
volatile unsigned int tick_cnt;

#if 0
/****************************************************************************/
void tick_measure()
{
  unsigned int lastwake;
  unsigned int diffwake, thiswake;

  TB0CN = 0x0503;
  TB0CN |= 0x0004; // enable timer

  tick_init();

  lastwake = 0xFFFF;
  while(1)
  {
    if (flag_400ms) {
      flag_400ms = 0;
      thiswake = TB0V;
      if (thiswake > lastwake)
        diffwake = thiswake - lastwake;
      else 
        diffwake = 0xFFFF - lastwake + thiswake + 1;
      lastwake = thiswake;
      maxq_printf(C"Wakeup @ %u, %u ms\r\n", diffwake, diffwake / ((XTAL_FREQ / 1000) >> 10));
    }
  }
}
#endif

/****************************************************************************/
void tick_init()
{
  WUT = WUT_VALUE; // set timer value
  WUTC = 0x01;  // start timer
}

/****************************************************************************/
unsigned int tick_gettime()
{
  return tick_cnt / TICKS_PER_SECOND;
}

/****************************************************************************/
#pragma vector = 7
__interrupt void tick_isr(void)
{
  WUTC = 0; // clear flag and disable timer
  WUT = WUT_VALUE; // set timer value
  WUTC = 0x01;  // start timer
  tick_cnt++;
  flag_100ms = 1;
  if ((tick_cnt & 0x1) == 0)
    flag_200ms = 1;
  if ((tick_cnt & 0x3) == 0)
    flag_400ms = 1;
  if ((tick_cnt & 0x7F) == 0)
    flag_13s = 1;
}
